package com.utooo.service.purchase;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.constant.ResultCodeConstant;
import com.utooo.dao.purchase.OrderInvoiceAssociationMapper;
import com.utooo.dao.purchase.OrderReconciliationDetailMapper;
import com.utooo.dao.purchase.OrderReconciliationMapper;
import com.utooo.dao.purchase.OrderReturnDetailMapper;
import com.utooo.dao.purchase.OrderReturnMapper;
import com.utooo.dao.purchase.PurchaseOrderMapper;
import com.utooo.dao.supplier.SupplierOrderReconciliationMapper;
import com.utooo.pojo.domain.purchase.order.OrderInvoiceAssociationDO;
import com.utooo.pojo.domain.purchase.order.OrderReconciliationDO;
import com.utooo.pojo.domain.purchase.order.OrderReconciliationDetailDO;
import com.utooo.pojo.domain.purchase.order.OrderReturnDO;
import com.utooo.pojo.domain.purchase.order.OrderReturnDetailDO;
import com.utooo.pojo.domain.purchase.order.PurchaseOrderDO;
import com.utooo.pojo.domain.supplier.settlement.SupplierOrderReconciliationDO;
import com.utooo.pojo.dto.common.RestResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

@Service
@Slf4j
public class OrderReconciliationServiceImpl extends ServiceImpl<OrderReconciliationMapper, OrderReconciliationDO>
        implements OrderReconciliationService {
    @Resource
    private SupplierOrderReconciliationMapper supplierOrderReconciliationMapper;
    @Resource
    private OrderReconciliationDetailMapper orderReconciliationDetailMapper;
    @Resource
    private OrderReturnMapper orderReturnMapper;
    @Resource
    private OrderReturnDetailMapper orderReturnDetailMapper;
    @Resource
    private PurchaseOrderMapper purchaseOrderMapper;
    @Resource
    private OrderInvoiceAssociationMapper orderInvoiceAssociationMapper;

    @Override
    public RestResult<String> confirmAndAddReconciliation(String id) {
        OrderReconciliationDO orderReconciliation = this.getById(id);
        if (orderReconciliation == null) {
            log.error("采购方订单对账记录为空，请检查！");
            return new RestResult<>(ResultCodeConstant.CODE_400, "采购方订单对账记录为空");
        }

        SupplierOrderReconciliationDO supplierOrderReconciliation = supplierOrderReconciliationMapper
                .selectOne(new LambdaQueryWrapper<SupplierOrderReconciliationDO>()
                        .eq(SupplierOrderReconciliationDO::getPurchaseOrderReconciliationId, id));
        if (supplierOrderReconciliation != null) {
            log.error("已确认，请勿重复提交！");
            return new RestResult<>(ResultCodeConstant.CODE_400, "已确认，请勿重复提交！");
        }
        // 待供方确认
        orderReconciliation.setStatus("2");
        this.updateById(orderReconciliation);
        supplierOrderReconciliation = new SupplierOrderReconciliationDO();
        BeanUtil.copyProperties(orderReconciliation, supplierOrderReconciliation, IGNORED_PROPERTIES);
        supplierOrderReconciliation.setPurchaseOrderReconciliationId(id);
        supplierOrderReconciliationMapper.insert(supplierOrderReconciliation);
        String orderReconciliationId = supplierOrderReconciliation.getId();

        List<OrderReconciliationDetailDO> orderReconciliationDetails =
                orderReconciliationDetailMapper.selectList(new LambdaQueryWrapper<OrderReconciliationDetailDO>()
                        .eq(OrderReconciliationDetailDO::getForeignId, id));
        if (CollUtil.isNotEmpty(orderReconciliationDetails)) {
            CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(IGNORED_PROPERTIES);
            List<OrderReconciliationDetailDO> details =
                    BeanUtil.copyToList(orderReconciliationDetails, OrderReconciliationDetailDO.class, copyOptions);
            details.forEach(i -> i.setForeignId(orderReconciliationId));
            orderReconciliationDetailMapper.insert(details);
        }
        return new RestResult<>(ResultCodeConstant.CODE_200, ResultCodeConstant.CODE_200_MSG);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateOrderReconciliation(String orderReturnId) {
        OrderReturnDO orderReturn = orderReturnMapper.selectById(orderReturnId);
        if (orderReturn == null) {
            log.error("退货订单记录为空，请检查！");
            return;
        }

        List<OrderReturnDetailDO> orderReturnDetails =
                orderReturnDetailMapper.selectList(new LambdaQueryWrapper<OrderReturnDetailDO>()
                        .eq(OrderReturnDetailDO::getForeignId, orderReturnId));
        if (CollUtil.isEmpty(orderReturnDetails)) {
            log.error("退货订单记录明细为空，请检查！");
            return;
        }

        PurchaseOrderDO purchaseOrder = purchaseOrderMapper.selectOne(new LambdaQueryWrapper<PurchaseOrderDO>()
                .eq(PurchaseOrderDO::getId, orderReturn.getOrderNo()));
        if (purchaseOrder == null) {
            log.error("采购订单不存在, orderNo: {}", orderReturn.getOrderNo());
            return;
        }

        // 生成订单业务对账单
        OrderReconciliationDO orderReconciliation = new OrderReconciliationDO();
        BeanUtil.copyProperties(orderReturn, orderReconciliation, IGNORED_PROPERTIES);
        orderReconciliation.setReconciliationNo(this.generateReconciliationNo());
        orderReconciliation.setTotalReconciliationQuantity(orderReturn.getTotalReturnQuantity());
        orderReconciliation.setExpectedAmountIncludingTax(orderReturn.getReturnAmountIncludingTax());
        orderReconciliation.setPurchaser(purchaseOrder.getPurchaser());
        orderReconciliation.setReconciliationType("2");
        orderReconciliation.setStatus("1");
        this.save(orderReconciliation);

        CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(IGNORED_PROPERTIES);
        List<OrderReconciliationDetailDO> orderReconciliationDetails =
                BeanUtil.copyToList(orderReturnDetails, OrderReconciliationDetailDO.class, copyOptions);
        orderReconciliationDetails.forEach(i -> {
            i.setForeignId(orderReconciliation.getId());
            i.setSourceDocumentNo(orderReturn.getReturnNo());
        });
        orderReconciliationDetailMapper.insert(orderReconciliationDetails);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<String> withdrawReconciliation(String id) {
        OrderReconciliationDO orderReconciliationDO = this.getById(id);
        if (orderReconciliationDO == null) {
            log.error("采购方订单对账单不存在，请检查！");
            return new RestResult<>(ResultCodeConstant.CODE_400, "采购方订单对账单不存在，请检查！");
        }
        List<OrderInvoiceAssociationDO> orderInvoiceAssociations =
                orderInvoiceAssociationMapper.selectList(new LambdaQueryWrapper<OrderInvoiceAssociationDO>()
                        .eq(OrderInvoiceAssociationDO::getSourceDocumentNo, id));
        if (CollUtil.isNotEmpty(orderInvoiceAssociations)) {
            log.error("该采购方订单对账单已关联发票，不可撤回！");
            return new RestResult<>(ResultCodeConstant.CODE_400, "该采购方订单对账单已关联发票！");
        }

        orderReconciliationDO.setStatus("1");
        this.updateById(orderReconciliationDO);
        SupplierOrderReconciliationDO supplierOrderReconciliation = supplierOrderReconciliationMapper
                .selectOne(new LambdaQueryWrapper<SupplierOrderReconciliationDO>()
                        .eq(SupplierOrderReconciliationDO::getPurchaseOrderReconciliationId, id));
        if (supplierOrderReconciliation == null) {
            log.info("供应商订单对账单不存在，已被删除！");
            return new RestResult<>(ResultCodeConstant.CODE_200, ResultCodeConstant.CODE_200_MSG);
        }
        String reconciliationId = supplierOrderReconciliation.getId();
        supplierOrderReconciliationMapper.deleteById(reconciliationId);
        orderReconciliationDetailMapper.delete(new LambdaQueryWrapper<OrderReconciliationDetailDO>()
                .eq(OrderReconciliationDetailDO::getForeignId, reconciliationId));
        return new RestResult<>(ResultCodeConstant.CODE_200, ResultCodeConstant.CODE_200_MSG);
    }

    @Override
    public String generateReconciliationNo() {
        String prefix = "DZ";
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<OrderReconciliationDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(OrderReconciliationDO::getReconciliationNo, prefix + datePart);
        queryWrapper.orderByDesc(OrderReconciliationDO::getReconciliationNo);
        queryWrapper.last("LIMIT 1");
        OrderReconciliationDO orderReconciliationDO = this.getOne(queryWrapper);

        // 生成序列号
        int maxSequence = 0;
        if (orderReconciliationDO != null) {
            String reconciliationNo = orderReconciliationDO.getReconciliationNo();
            maxSequence = Integer.parseInt(reconciliationNo.substring((prefix + datePart).length()));
        }
        int nextSequence = maxSequence + 1;
        String sequencePart = String.format("%03d", nextSequence);
        return prefix + datePart + sequencePart;
    }

}